
/*
 * C/C++ Lessons Program
 * 
 * Copyright (c) 2012 Ken Zhang (cpp.china@gmail.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
	const char *filename = "hello.txt";
	const char *text = "Welcome to the C World!";

	// open a txt file to write something
	int fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC);
	if (fd < 0) {
		printf("Failed to create '%s'.\n", filename);
		return -1;
	}
	else {
		printf("Created a new file '%s' with fd [%d]\n", filename, fd);
	}

	// if no O_WRONLY, write will be failed
	// if no O_TRUNC, the write operation only overwrite the part with its length
	int n = write(fd, text, strlen(text));
	if (n < 0) {
		perror("Write failed");
		close(fd);
		return -2;
	}
	else {
		printf("Write %d bytes to file '%s'.\n", n, filename);
	}
	close(fd);

	// open it to read the content out
	char buffer[128];
	fd = open(filename, O_RDONLY);
	if (fd < 0) {
		printf("Failed to open file '%s' to read.\n", filename);
		close(fd);
		return -3;
	}

	memset(buffer, 0, sizeof(buffer));
	read(fd, buffer, sizeof(buffer) - 1);
	printf("Read from file: '%s'\n", buffer);
	close(fd);

	return 0;
}


